﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvdDonk.Bomberman.Menu;
using MvdDonk.Bomberman.Screens.Base;
using Microsoft.Xna.Framework;

namespace MvdDonk.Bomberman.Screens
{
    class HostServerScreen : MenuScreen
    {
        MenuEntry startGame;
        MenuEntry loadingGameMenuEntry;

        public HostServerScreen()
            : base("Clients joined", MenuOrientation.Vertical)
        {
            // Create our menu entries.
            loadingGameMenuEntry = new MenuEntry("Waiting for clients to connect...");
            loadingGameMenuEntry.Selectable = false;

            startGame = new MenuEntry("Start game");

            // Hook up menu event handlers.
            startGame.Selected += StartGame_Selected;

            // Add entries to the menu.

            MenuEntries.Add(loadingGameMenuEntry);

            Bomberman.Instance.NetworkManager.StartServer();
        }

        void StartGame_Selected(object sender, EventArgs e)
        {
            //Join urself to the server
            Bomberman.Instance.NetworkManager.JoinServer(Bomberman.Instance.NetworkManager.Server.EndPoint);

            //TODO Check if connected to self?

            //TODO Send to all clients we are gonne start teh game
            ScreenManager.AddScreen(new GameplayScreen());
        }

        public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            if (Bomberman.Instance.EntityManager.Players.Count == 0)
            {
                if (!MenuEntries.Contains(loadingGameMenuEntry))
                {
                    MenuEntries.Clear();
                    MenuEntries.Add(loadingGameMenuEntry);
                }
            }
            else
            {
                //Add the menu 'start game' menu item on top
                if (!MenuEntries.Contains(startGame))
                    MenuEntries.Add(startGame);

                //Add new connected players
                foreach (var player in Bomberman.Instance.EntityManager.Players)
                {
                    if (!MenuEntries.Any(m => m.Text == player.ClientName))
                    {
                        var entry = new MenuEntry(player.ClientName);
                        entry.Selectable = false;
                        MenuEntries.Add(entry);
                    }
                }

                //Remove disconnected players
                MenuEntries.RemoveAll(m => m != startGame && !Bomberman.Instance.EntityManager.Players.Any(p => p.ClientName == m.Text));
            }
        }

        protected override void OnCancel()
        {
            Bomberman.Instance.NetworkManager.KillServer();
            base.OnCancel();
        }
    }
}
